package com.lbs.jiepiaisi.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.activity.VinIndexActivity;
import com.lbs.jiepiaisi.base.BaseFragment;
import com.lbs.jiepiaisi.base.ErrorException;
import com.lbs.jiepiaisi.base.ProgressObserver;
import com.lbs.jiepiaisi.bean.UserEntity;
import com.lbs.jiepiaisi.bean.VinList;
import com.lbs.jiepiaisi.biz.LoginAccountBiz;
import com.lbs.jiepiaisi.config.Api;
import com.lbs.jiepiaisi.manager.SharePreferenceManager;
import com.lbs.jiepiaisi.utils.ButtonUtil;
import com.lbs.jiepiaisi.utils.Constant;

import com.lbs.jiepiaisi.utils.RxSchedulers;
import com.lbs.jiepiaisi.utils.ToastUtil;
import com.lbs.jiepiaisi.view.WaitingDialogControll;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 时间：2017/6/20 14:01
 * 作用：车架号登录
 */

public class VinLoginFragment extends BaseFragment {
    private Button butlogin;
    private CheckBox cb_remember;
    private EditText edit_account_number;//账号
    private EditText edit_password;//密码
    public SharePreferenceManager mSharePreference = null;
    private UserEntity userEntity;

    private LoginReceiver loginReceiver;

    /**
     * 此方法可以得到上下文对象
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View initView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fragment_platform_vin_login, null);
        loginReceiver = new LoginReceiver();
        mContext.registerReceiver(loginReceiver, new IntentFilter(Constant.ACCOUNT_VIN_LOGIN));
        mSharePreference = new SharePreferenceManager(mContext);
        return view;
    }

    @Override
    protected void getExtras(View view) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mContext.unregisterReceiver(loginReceiver);
    }

    @Override
    protected void findView(View view) {
        butlogin = (Button) view.findViewById(R.id.btn_platform_login);
        cb_remember = (CheckBox) view.findViewById(R.id.cb_remember);
        edit_account_number = (EditText) view.findViewById(R.id.edit_account_number);
        edit_password = (EditText) view.findViewById(R.id.edit_password);
        //记住账号密码操作
        String number = mSharePreference.getString(Constant.FRAME_NUMBER, "");
        String password = mSharePreference.getString(Constant.FRAME_PASSWORD, "");
        if (number.equals("") && password.equals("")) {
            cb_remember.setChecked(false);
        } else {
            cb_remember.setChecked(true);
            if (password.equals("")) {
                //取出来为空时不设置
                cb_remember.setChecked(false);
                //设置账号
                edit_account_number.setText(number);
            } else {//不为空时设置
                //设置账号
                edit_account_number.setText(number);
                //设置密码
                edit_password.setText(password);
            }
        }
    }

    @Override
    protected void setListener(View view) {
        butlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ButtonUtil.isFastClick()) {
                    String account_number = edit_account_number.getText().toString();
                    String password = edit_password.getText().toString();

                    if (account_number == null || account_number.length() == 0 || password == null || password.length() <= 5) {
                        ToastUtil.show("车架号或密码错误");
                        return;
                    }

//                    userEntity = new UserEntity();
//                    userEntity.setAccount_number(edit_account_number.getText().toString());
//                    userEntity.setAccount_password(edit_password.getText().toString());
//
//                    Api.getInstance().createService()
//                            .vinLogin(account_number,password)
//                            .compose(RxSchedulers.observableIO2Main(mContext))
//                            .subscribe(new ProgressObserver<VinLoginBean>(mContext, true) {
//                                @Override
//                                public void onSuccess(VinLoginBean result) {
//                                    //Log.e("vinsuccess",result+"");
//                                    if (result == null || result.getResult() == null) {
//                                        return;
//                                    }
//
//                                    VinLoginBean _result = result;
//
//                                    //List<VinLoginBean.Item> items = result.getResult();
//                                    for (VinLoginBean.Item item : _result.getResult()) {
//                                        if (item.getPoint() == null || item.getPoint().getLat() == 0) {
//                                            _result.getResult().remove(item);
//                                        }
//                                    }
////                                    for (int i = 0; i < result.getResult().size(); i++) {
////                                        if (result.getResult().get(i).getPoint() == null || result.getResult().get(i).getPoint().getLat() == 0) {
////                                        }
//////                                        if (result.getResult().get(i).getPoint() != null && result.getResult().get(i).getPoint().getLat() != 0) {
//////                                            items.add(result.getResult().get(i));
//////                                        }
////                                    }
//
//                                    if (_result.getResult().size() == 0) {
//                                        ToastUtil.show("设备未定位，请定位后重新登录");
//                                        return;
//                                    }
//
//                                    //List<VinLoginBean.Item> ableItem = new ArrayList<>();
//                                    for (VinLoginBean.Item item : _result.getResult()) {
//                                        if (item.getMark().equals("D")) {
//                                            _result.getResult().remove(item);
//                                        }
//                                    }
//
//                                    if (_result.getResult().size() == 0) {
//                                        ToastUtil.show("该设备已被禁用");
//                                        return;
//                                    }
//
//                                    ToastUtil.show("登录成功");
//                                    mSharePreference.put(Constant.FRAME_NUMBER, edit_account_number.getText().toString());//存入账号
//                                    if (cb_remember.isChecked()) {
//                                        String password = edit_password.getText().toString();
//                                        mSharePreference.put(Constant.FRAME_PASSWORD, password);//存入密码
//                                    } else {
//                                        mSharePreference.put(Constant.FRAME_PASSWORD, "");
//                                    }
//                                    Intent intentCar = new Intent(getActivity(), VinIndexActivity.class);
//                                    intentCar.putExtra("_result", _result);
//                                    intentCar.putExtra("userEntity", userEntity);
//                                    startActivity(intentCar);
//
//                                }
//                                @Override
//                                public void onFailure(ErrorException e) {
//
//                                }
//                            });

                    if ((account_number == null || account_number.length() == 0) && (password == null || password.length() <= 5)) {
                        Toast.makeText(mContext, "车架号或密码错误", Toast.LENGTH_SHORT).show();
                    } else {
                        WaitingDialogControll.showWaitingDialog(getContext());
                        userEntity = new UserEntity();
                        userEntity.setAccount_number(edit_account_number.getText().toString());
                        userEntity.setAccount_password(edit_password.getText().toString());
                        new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                LoginAccountBiz loginAccountBiz = new LoginAccountBiz();
                                loginAccountBiz.loginByCarBiz(userEntity);
                            }
                        }.start();
                    }
                }
            }
        });
    }

    private boolean isTake = false;

    @Override
    public void onResume() {
        super.onResume();
        isTake = false;
    }

    class LoginReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                WaitingDialogControll.dismissWaitingDialog();
                VinList VinList = (VinList) intent.getSerializableExtra(Constant.KEY_DATA);
                String code = VinList.getStatus();
                VinList mData = new VinList();

                mData.setLoginFailBeans(VinList.getLoginFailBeans());
                mData.setMessage(VinList.getMessage());
                mData.setStatus(VinList.getStatus());
                mData.setResult(new ArrayList<com.lbs.jiepiaisi.bean.VinList.Vin>());
                List<String> bs = new ArrayList<>();
                if ((Constant.STATUS_OK + "").equals(code)) {
                    if (VinList.getResult() == null) {
                        return;
                    }

                    for (int i = 0; i < VinList.getResult().size(); i++) {
                        if (VinList.getResult().get(i).getPoint() == null) {
                            VinList.getResult().remove(i);
                        }
                        if (VinList.getResult().get(i).getMark().equals("D")) {
                            bs.add(VinList.getResult().get(i).getEqNo());
                        } else {
                            mData.getResult().add(VinList.getResult().get(i));
                        }
                    }

                    if (VinList.getResult().size() == 0) {
                        Toast.makeText(mContext, "该设备未激活，请激活后重新登录", Toast.LENGTH_LONG).show();
                        return;
                    }

                    if (mData.getResult().size() == 0) {
                        Toast.makeText(mContext, "该设备已经被禁用", Toast.LENGTH_LONG).show();
                        return;
                    }
                    if (!isTake) {
                        isTake = true;
                        Toast.makeText(mContext, "登录成功", Toast.LENGTH_SHORT).show();
                        mSharePreference.put(Constant.FRAME_NUMBER, edit_account_number.getText().toString());//存入账号
                        if (cb_remember.isChecked()) {
                            String password = edit_password.getText().toString();
                            mSharePreference.put(Constant.FRAME_PASSWORD, password);//存入密码
                        } else {
                            mSharePreference.put(Constant.FRAME_PASSWORD, "");
                        }
                        Intent intentCar = new Intent(getActivity(), VinIndexActivity.class);
                        intentCar.putExtra("vinList", mData);
                        intentCar.putExtra("userEntity", userEntity);
                        startActivity(intentCar);
                    }
                } else if ((Constant.STATUS_NETWORK_ERROR + "").equals(code)) {
                    Toast.makeText(mContext, "请检查网络连接", Toast.LENGTH_SHORT).show();
                } else if ((Constant.STATUS_NO_NET + "").equals(code)) {
                    Toast.makeText(mContext, "请检查网络连接", Toast.LENGTH_SHORT).show();
                } else if ((Constant.STATUS_NULL + "").equals(code)) {
                    Toast.makeText(mContext, "车架号或密码错误，请重新输入", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(mContext, "连接超时", Toast.LENGTH_SHORT).show();
            }
        }
    }
}